<?php
class BDA_Database {
    public static function init() {
        // Initialization if needed
    }
    
    public static function install_tables() {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        
        $charset_collate = $wpdb->get_charset_collate();
        
        // User actions table
        $sql1 = "CREATE TABLE {$wpdb->prefix}analytics_user_actions (
            id BIGINT(20) NOT NULL AUTO_INCREMENT,
            user_id BIGINT(20),
            session_id VARCHAR(32),
            action_type VARCHAR(50) NOT NULL,
            ip_address VARCHAR(45),
            user_agent TEXT,
            created_at DATETIME NOT NULL,
            PRIMARY KEY (id),
            KEY user_id (user_id),
            KEY session_id (session_id)
        ) {$charset_collate};";
        
        // Purchases table
        $sql2 = "CREATE TABLE {$wpdb->prefix}analytics_purchases (
            id BIGINT(20) NOT NULL AUTO_INCREMENT,
            order_id BIGINT(20) NOT NULL,
            user_id BIGINT(20),
            product_id BIGINT(20) NOT NULL,
            category_id BIGINT(20),
            quantity INT NOT NULL,
            total_price DECIMAL(10,2) NOT NULL,
            purchase_date DATETIME NOT NULL,
            PRIMARY KEY (id),
            KEY order_id (order_id),
            KEY user_id (user_id),
            KEY product_id (product_id)
        ) {$charset_collate};";
        
        dbDelta($sql1);
        dbDelta($sql2);
    }
    
    public static function uninstall_tables() {
        global $wpdb;
        $tables = [
            "{$wpdb->prefix}analytics_user_actions",
            "{$wpdb->prefix}analytics_purchases"
        ];
        
        foreach ($tables as $table) {
            $wpdb->query("DROP TABLE IF EXISTS {$table}");
        }
    }
    
    public static function query($sql) {
        global $wpdb;
        return $wpdb->get_results($sql);
    }
}